package com.heima.behavior.service.impl;


import com.heima.behavior.dtos.ArticleBehaviorDto;
import com.heima.behavior.service.ApBehaviorService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApBehaviorServiceImpl implements ApBehaviorService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 加载文章关系
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleBehaviorDto dto) {
        //判断参数
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取用户id
        ApUser apUser = ApThreadLocal.getApUser();
        if (apUser==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        if (apUser.getId()==0){
            return ResponseResult.okResult(405,"游客身份禁止，需进行登录");
        }
        //定义几个变量这几个变量是前台的变量
        Boolean islike=false,isunlike=false,iscollection=false,isfollow=false;
        //3.查询是否关注过       redis
        String followKey="USER_FOLLOW_"+apUser.getId();
        Boolean followFlag = stringRedisTemplate.opsForHash().hasKey(followKey, dto.getAuthorId().toString());
        if (followFlag){//表示存在
            isfollow=true;
        }
        //4.查询是否点赞过redis
        String likeKey="USER_LIKES_"+dto.getArticleId();
        Boolean likeFlag = stringRedisTemplate.opsForHash().hasKey(likeKey, apUser.getId().toString());
        if (likeFlag){//表示存在
            islike=true;
        }
        //5.查询是否不喜欢过redis
        String unlikeKey="USER_UNLIKES_"+dto.getArticleId();
        Boolean unlikeFlag = stringRedisTemplate.opsForHash().hasKey(unlikeKey, apUser.getId().toString());
        if (unlikeFlag){//表示存在
            isunlike=true;
        }
        //6.查询是否收藏过redis
        String iscollectionKey="USER_COLLECTION_"+dto.getArticleId();
        Boolean iscollectionFlag = stringRedisTemplate.opsForHash().hasKey(iscollectionKey, apUser.getId().toString());
        if (iscollectionFlag){//表示存在
            iscollection=true;
        }
        //7.封装数据，并返回
        Map map=new HashMap();
        map.put("islike",islike);
        map.put("iscollection",iscollection);
        map.put("isfollow",isfollow);
        map.put("isunlike",isunlike);
        return ResponseResult.okResult(map);
    }
}
